package com.cloud.shopping.pay.config;

import com.github.wxpay.sdk.IWXPayDomain;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author John.zhang
 * @version Id: WXPayConfig, v 1.0 2021/1/6 11:50 ZhiYong Exp $
 */
@Component
public class WeChatPayConfig extends WXPayConfig {

    /**
     * 应用ID
     */
    @Value("${pay.weChat.appId}")
    private String appId;

    /**
     * 商户号
     */
    @Value("${pay.weChat.mchID}")
    private String mchID;

    /**
     * 秘钥
     */
    @Value("${pay.weChat.key}")
    private String key;

    /**
     * 回调地址
     */
    @Value("${pay.weChat.notifyUrl}")
    private String notifyUrl;

    /**
     * 证书路径
     */
    @Value("${pay.weChat.certPath}")
    private String certPath;

    /**
     * 证书字节数组
     */
    private byte[] certData;


    @Override
    public String getAppID() {
        return this.appId;
    }

    @Override
    public String getMchID() {
        return this.mchID;
    }

    @Override
    public String getKey() {
        return this.key;
    }

    /**
     * 获取商户证书内容
     * @return InputStream
     */
    @Override
    public InputStream getCertStream() {
        if(certData==null){
            synchronized (WeChatPayConfig.class){
                try {
                    if(certData==null) {
                        File file = new File(certPath);
                        InputStream certStream = new FileInputStream(file);
                        this.certData = new byte[(int) file.length()];
                        certStream.read(this.certData);
                        certStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    /**
     * 获取WXPayDomain, 用于多域名容灾自动切换
     * @return IWXPayDomain
     */
    @Override
    public IWXPayDomain getWXPayDomain() {
        IWXPayDomain iwxPayDomain = new IWXPayDomain() {
            @Override
            public void report(String domain, long elapsedTimeMillis, Exception ex) {
            }
            @Override
            public DomainInfo getDomain(WXPayConfig config) {
                return new DomainInfo(WXPayConstants.DOMAIN_API, true);
            }
        };
        return iwxPayDomain;
    }
}
